#!/usr/bin/env bash
#
# narsil-ntpserver.sh - Change NTP Server
# Seaton Jiang <hi@seatonjiang.com>
#
# The latest version of Narsil can be found at:
# https://github.com/seatonjiang/narsil
#
# Copyright (C) 2023 Seaton Jiang
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

function narsil_ntpserver()
{
    msg_info '\n%s\n' "[${STATS}] Change NTP Server"

    timedatectl set-ntp true

    dnf install -y chrony >/dev/null 2>&1

    cp ./config/chrony.conf /etc/chrony.conf

    narsil_ntpserver='ntp.tencent.com'

    if [[ ${METADATA} == "Y" ]]; then
        if [ -n "$(wget -qO- -t1 -T2 metadata.tencentyun.com)" ]; then
            ntpserver='time1.tencentyun.com time2.tencentyun.com time3.tencentyun.com time4.tencentyun.com time5.tencentyun.com'
        fi
    fi

    if [ "${narsil_ntpserver}" != "${NTP_SERVER}" ]; then
        ntpserver=${NTP_SERVER}
    fi

    local server

    for server in ${ntpserver}; do
        echo "server ${server} iburst" >> /etc/chrony.conf
    done

    systemctl restart chronyd.service

    if [[ ${VERIFY} == "Y" ]]; then
        msg_notic '\n%s\n' "• NTP synchronization status"
        chronyc tracking
        msg_notic '\n%s\n' "• NTP pools"
        chronyc sources
        msg_notic '\n%s\n' "• File Content: /etc/chrony.conf"
        grep -Ev '^#|^$' /etc/chrony.conf | uniq
    else
        msg_succ '%s\n' "Success, this operation is completed!"
    fi

    sleep 1

    ((STATS++))
}
